package com.shell.guard.utils;

import com.shell.bee.base.utils.JsonUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.entity.mvc.RetMsg;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

public class HttpUtil
{
  public static String NOT_LOGGED_IN_MSG = "未登录或登陆超时";
  
  public static boolean isAjax(HttpServletRequest request)
  {
    String requestType = request.getHeader("X-Requested-With");
    if ((!StringUtil.emptyAndNull(requestType)) && ("XMLHttpRequest".equals(requestType))) {
      return true;
    }
    return false;
  }
  
  public static PrintWriter getWriterFromResponse(HttpServletResponse response)
  {
    try
    {
      return response.getWriter();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    return null;
  }
  
  public static void retMsgNotLoggedIn(HttpServletResponse response)
  {
    RetMsg msg = new RetMsg("tologin", NOT_LOGGED_IN_MSG);
    
    response.setHeader("Content-Type", "application/json;charset=utf-8");
    response.setCharacterEncoding("UTF-8");
    PrintWriter writer = getWriterFromResponse(response);
    try
    {
      writer.print(JsonUtil.toJson(msg));
    }
    catch (Exception e1)
    {
      e1.printStackTrace();
    }
  }
  
  public static Object retMsgNotLoggedInForCtr(HttpServletResponse response)
    throws Exception
  {
    RetMsg msg = new RetMsg("tologin", NOT_LOGGED_IN_MSG);
    HttpHeaders header = new HttpHeaders();
    header.add("Content-Type", "application/json;charset=utf-8");
    return new ResponseEntity(JsonUtil.toJson(msg), header, HttpStatus.OK);
  }
  
  public static void cleanCookie(HttpServletRequest request)
  {
    request.getSession().invalidate();
    if ((null != request.getCookies()) && (request.getCookies().length > 0))
    {
      Cookie cookie = request.getCookies()[0];
      cookie.setMaxAge(0);
    }
  }
  
  public static String getCookieValue(HttpServletRequest request, String cookieKey)
  {
    String ret = null;
    Cookie[] cookies = request.getCookies();
    if (null != cookies) {
      for (Cookie cookie : cookies) {
        if (cookie.getName().equals(cookieKey))
        {
          ret = cookie.getValue();
          break;
        }
      }
    }
    return ret;
  }
}